package dao;

import core.Login;
import core.TestData;
import core.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Stateless;


/**
 *
 * @author Michal Horak
 */
@Stateless
public class UserDAO implements IUser{

    @Override
    public void createUser(User user) {
        if (user == null){
            throw new RuntimeException("null paprametr");
        } else {
            Integer userId = this.getMaxUserId();
            user.setId(userId);
            TestData.USERS_TABLE.put(userId, user);
        }
    }

    @Override
    public void updateUser(User user) {
         if(user == null || !TestData.USERS_TABLE.containsKey(user.getId()))
        {
            throw new RuntimeException("Uživatelské jméno je již obsazené" );
        }
        TestData.USERS_TABLE.put(user.getId(), user);
    }

    @Override
    public void deleteUser(User user) {
         if(user == null)
        {
            throw new RuntimeException("null");
        }
        TestData.USERS_TABLE.remove(user.getId());
    }

    @Override
    public User findUser(int userId) {
        return TestData.USERS_TABLE.get(userId);
    }

    @Override
    public List<User> findAllUsers() {

       return new ArrayList<User>(TestData.USERS_TABLE.values());
    }

    @Override
    public User findUser(String username) {
        User a = null;
        
        for (Map.Entry<Integer, User> entry : TestData.USERS_TABLE.entrySet()){
            a = entry.getValue();
            if (a.getLogin().getUsername() == null ? username == null : a.getLogin().getUsername().equals(username)){
               return a; 
            }
        }
        return a;
        
    }
    
    @Override
    public User testLogin(Login login){
        
        for (Map.Entry<Integer, User> entry : TestData.USERS_TABLE.entrySet()){
            User u = entry.getValue();
            if (u.getLogin().equals(login)){
                return u;
            }
        }
        
        return null;
    }
    
    protected Integer getMaxUserId()
    {
        Set<Integer> keys = TestData.USERS_TABLE.keySet();
        Integer maxId = 1;
        for (Integer key : keys)
        {
            if(key > maxId)
            {
                maxId = key;
            }
        }
        return maxId;
    }

    
}
